package edu.gatech.cs2340.tigershroud;

import java.util.Calendar;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
/**
 * The SearchActivity class allows the user to select options for search criteria,
 * makes calls to the database to search by criteria, and returns the results in list form
 * @author []
 * @version 9.0x, Build April 3, 2012.
 */
public class SearchActivity extends ListActivity implements RadioGroup.OnCheckedChangeListener
{
	//class variables
	private TodoDataSource ds;
	private Button bsearch, bback;
	private RadioGroup rsearch1, rorder;
	private RadioButton rad;
	private TextView count;
	private EditText search;
	private ListView lv;
	private List<Task> tlist;
	private int rselect1, rselect2;
	private String key, order, num, cat, uname, utype;
	private int mYear, mMonth, mDay;
	private Calendar c;

    static final int DATE_DIALOG_ID = 0;
	
	/**
	 * The onCreate method is a default android method that is called when the
	 * activity is first started. This onCreate method assigns passed objects to variables, 
	 * opens the database, determines the layout of
	 * the activity, and sets listeners for items within the activity
	 * @param saveInstanceState the Bundle name value pair that represents the state of the object
	 *
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		//default call to super class
		super.onCreate(savedInstanceState);
		
		//setup layout with search.xml
	    setContentView(R.layout.search);
	    
	    Log.d("SEARCH", "inside search activity");
	    
	    //open the database
	    ds = new TodoDataSource(this);
	    ds.open();
	    Log.d("SEARCH", "opened database");
	    
	    uname = getIntent().getExtras().getString("uname");
        utype = getIntent().getExtras().getString("utype");
        
	    c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
	    
	    //setup widgets in the activity
	    search = (EditText) findViewById(R.id.etsearch);
	    bsearch = (Button) findViewById(R.id.bsearch);
	    bback = (Button) findViewById(R.id.bback);
	    rsearch1 = (RadioGroup) findViewById(R.id.rgsearch1);
	    rorder = (RadioGroup) findViewById(R.id.rgorder);
	    count = (TextView) findViewById(R.id.tvcount);

	    //add listeners to items
	    rsearch1.setOnCheckedChangeListener(this);
	    rorder.setOnCheckedChangeListener(this);
	    order = "ASC";
	    rselect2 = -1;
	    Log.d("SEARCH", "back in oncreate()");
	  
	    //initially the list of tasks has all tasks
	    refresh(display());
	    
	    final CharSequence[] items = {"Miscellaneous", "Personal", "School", "Work"};

	    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setTitle("Pick a category");
	    builder.setItems(items, new DialogInterface.OnClickListener() 
	    {
	        public void onClick(DialogInterface dialog, int item) 
	        {
	            cat = (String) items[item];
	            tlist = ds.searchByCategory(cat, order, utype);
	            refresh(tlist);
	        }
	    });
	    
	    //setup list view
       	lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the user is taken to another activity that
        	 * lets the user view the item.
        	 * @param parent the AdapterView of the Activity that contains the item
        	 * @param view the View that is generated by the parent activity
        	 * @id the id number of the item in the R.java file
        	 */
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        	{	//close database
        		ds.close();
        		//get the task that was clicked on 
        		Task t = (Task) lv.getItemAtPosition(position);
        		//Give user feedback
        		Toast.makeText(SearchActivity.this, t.getTaskName() + " selected...", Toast.LENGTH_LONG).show();
        		//start new activity for viewing the clicked Task
        		Intent i = new Intent(SearchActivity.this, TaskViewActivity.class);
        		i.putExtra("clickedTask", t);
        		startActivity(i);
            }
        });
	    
        /**
    	 * This method inside the anonymous inner-class OnClickListener
    	 * determines the behavior of the application when the item is clicked.
    	 * When the item is clicked, the user is taken to another activity that
    	 * lets the user view the item.
    	 * @param view the View that is generated by the parent activity
    	 */
	    bsearch.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
	     	{
	    		key = search.getText().toString();
	    		
	       		if(rselect2 == -1)
	    		{
	    			Log.d("SEARCH", "order not choose, default to asc");
	    			rselect2 = R.id.rbasc;
	        		rad = (RadioButton) findViewById(rselect2);
	        		order = rad.getText().toString();
	    		}
	       		
				switch(rselect1)
				{
					case R.id.rbtname:
						tlist = ds.searchByTaskName(key, order, utype);
						refresh(tlist);
	     				Log.d("TODO", "filter by task name");
	     				break;
	     			case R.id.rbdate:
	     				showDialog(DATE_DIALOG_ID);
	     				Log.d("TODO", "filter by date");
	     				break;
	     			case R.id.rbcat:
	     				AlertDialog alert = builder.create();
	     				alert.show();
	     				Log.d("TODO", "filter by category");
	     				break;
	     			case R.id.rbcomp:
	     				tlist = ds.searchByStatus(key, "1", utype);
	     				Log.d("TODO", "filter by complete");
	     				break;
	     			default:
	     				tlist = ds.searchByCurrentUserName(order);
	     				Log.d("TODO", "filter, by username");
				}
	     	}
	    });
	    
	    bback.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
			{
				ds.close();
				finish();
			}
		});
	}

	public void onCheckedChanged(RadioGroup rg, int arg1) 
	{
		if(rg == rsearch1)
		{
			rselect1 = rg.getCheckedRadioButtonId();
			Log.d("SEARCH", "pressed rg1");
		}
		else if(rg == rorder)
		{
    		rselect2 = rg.getCheckedRadioButtonId();
       		if(rselect2 == -1)
    		{
    			rselect2 = R.id.rbasc;
    		}
    		rad = (RadioButton) findViewById(rselect2);
    		order = rad.getText().toString();
    		Log.d("SEARCH", order);
		}
	}
	
    @Override
	protected void onResume()
    {
    	super.onResume();
    	ds.open();
        refresh(display());
    }
    
    public void refresh(List<Task> t)
    {
        setListAdapter(new ArrayAdapter<Task>(getApplicationContext(), android.R.layout.simple_list_item_1, t));
        if(t.size() == 1)
        {
        	if((t.get(0)).getDnum() == -1)
        	{
        		num = "0";
        	}
        }
        else
        {
        	num = t.size() + "";
        }
        count.setText(num);
    }
    
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() 
    		{
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
                {
                    mYear = year;
                    mMonth = monthOfYear + 1;
                    mDay = dayOfMonth;
                    String df = "";
                    
            		if(mMonth < 10 && mDay > 9)
            		{
            			df = mYear + "0" + mMonth + "" + mDay;
            		}
            		else if(mDay < 10 && mMonth > 9)
            		{
            			df = mYear + "" + mMonth + "0" + mDay;
            		}
            		else if(mDay < 10 && mMonth < 10)
            		{
            			df = mYear + "0" + mMonth + "0" + mDay;
            		}
            		else if(mMonth > 9 && mDay > 9)
            		{
            			df = mYear + "" + mMonth + "" + mDay;
            		}
                    key = df + "000000";
                    
                    /*
     				tlist = ds.searchByDate(key, order, utype);
     				Log.d("TODO", "filter by date");
     				refresh(tlist);
     				*/
                    
                    ds.close();
    	        	Intent intent = new Intent(getApplicationContext(), DateFilterActivity.class);
        			intent.putExtra("utype", utype);
        			intent.putExtra("key", key);
        			intent.putExtra("order", order);
                    startActivity(intent);
                }
            };
    
    @Override
	protected Dialog onCreateDialog(int id) 
    {
        switch(id) 
        {
	        case DATE_DIALOG_ID:
	            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
        }
        return null;
    }
    
    public List<Task> display()
    {
		if(utype.equals("super"))
		{
			return ds.getAllTask(order);
		}
		return ds.getAllTaskForUser(order);
    }
}
